
<?php

//This is the main file for all the functions, database connections, queries, and session starts
session_start();
$dbconnect = pg_connect('host=dbsrv1 dbname=csc309g7 user=csc309g7 password=aiboid4p') || die();

/*Functions in Friend begin
 * 
 * */

 function add_to_friend_list($myuserid, $friendid)
 {
	$add_friend_query = "insert into friends values ($myuserid, $friendid)";	
	
	$add_friend_result = pg_query($add_friend_query);
	
	if(!$add_friend_result)
	{
		echo "<p>Error in adding friends</p>";
		
	}
	 
 }
 
 function check_friends($myuserid, $friendid)
 {
	 $check_friend_query = "select * from friends where userid = $myuserid and friends_with = $friendid ";	
	
	$check_friend_result = pg_query($check_friend_query);
	
	if (pg_num_rows($check_friend_result) != 0)
	{
		return 1;
	}
	
	return 0;
	 
 }
 
 
 /*Functions in Friend end
 * 
 * */

/*Functions in Games begin
 * 
 * */
 

 
 function draw_sort_bar_in_game($select_sort, $select_search, $search_term)
 {
	 echo "<div >
	
	<table border='0'>
		<tr>
			<td>Sort by:
			</td>
			<td>
			<select name='sort_by_select' onchange=\"javascript:document.forms['glf'].submit()\">";
				
				
				
				$sort_option_array =array("Time","Location","Sport","Creator");
				$search_option_array = array("Title","Location", "Sport","Creator");
				
				foreach($sort_option_array as $val) 
				{
    				if($sort_opt_chosen = $select_sort)
					{
						if($sort_opt_chosen == $val)
							echo "<option value='$val' selected>$val</option>";
						else
						{
							echo "<option value='$val' >$val</option>";
						}
						
					}
					else
					{
						echo "<option value='$val' >$val</option>";
					}
					
				}
				
		echo "				
				
			</select>
			</td>
			<td>search by: </td>
			<td>
				<select name='search_by_select'>";
				
				foreach($search_option_array as $val) 
				{
    				if($search_opt_chosen = $select_search)
					{
						if($search_opt_chosen == $val)
							echo "<option value='$val' selected>$val</option>";
						else
						{
							echo "<option value='$val' >$val</option>";
						}
						
					}
					else
					{
						echo "<option value='$val' >$val</option>";
					}
					
				}
				
				
				
				echo "
				</select>
			</td>
			<td><input type=\"text\" name=\"search_term\" value=\"$search_term\"/></td>
			<td><input type=\"submit\" value=\"search\" /></td>
			
		</tr>
	</table>
	
	</div>";
	
	if($sort_opt_chosen)
	{
		if ($sort_opt_chosen == $sort_option_array[0])
			$sort_by = " start_date, start_time, title, sport_name,location,username ";
		elseif ($sort_opt_chosen == $sort_option_array[1])
			$sort_by = " location,start_date, start_time, title, sport_name,username ";
		elseif ($sort_opt_chosen == $sort_option_array[2])
			$sort_by = " sport_name, start_date, start_time, title, location, username ";
		elseif ($sort_opt_chosen == $sort_option_array[3])
			$sort_by = " username, start_date, start_time, title, sport_name,location ";
	}
	else
	{
		 $sort_by = " start_date, start_time, title, sport_name,location,username ";
	}
	
	
	
	if($search_opt_chosen && $search_term )
	{
		if ($search_opt_chosen == $search_option_array[0])
			$and_like = " and title ILIKE '%$search_term%'  ";
		elseif ($search_opt_chosen == $search_option_array[1])
			$and_like = " and location_name ILIKE '%$search_term%'  ";
		elseif ($search_opt_chosen == $search_option_array[2])
			$and_like = " and sport_name ILIKE '%$search_term%'  ";
		elseif ($search_opt_chosen == $search_option_array[3])
			$and_like = " and username ILIKE '%$search_term%'  ";
	}	
			return $sort_by . ";" . $and_like; 
 }
 

function create_a_game($game_title,$sport_select,$start_date,$start_time,$location_select,$myuserid)
{
	
		
		$createGame_Query="insert into games values(default, ".$sport_select . ", ".$myuserid.",'".$start_date."','".$start_time."',".$location_select.",'".$game_title."')";
		$createGame_result = pg_query($createGame_Query);
		
		
		
		echo "<form action='Game.php' method='POST'>
		<table>
			<tr><td>";
		//echo $createGame_result;
		
		if($createGame_result)
		{
		
			echo "<label>Your game was created successfully!</label>\n";
		}
		else
		{
			echo "<label>Failed</label>\n";
		}	
		echo "</td></tr>
		<tr><td><input type='submit' Value='Return to game list'/></td></tr>
		</table>
		</form>";	
}

function delete_me_from_game($myuserid, $gameid)
{
	
	$delete_query = "delete from usergame where gameid = $gameid  and userid = $myuserid";	
	$delete_result = pg_query($delete_query);
	
	if(!$delete_result)
	{
		echo "<p>Deletion failed;</p>";
	}
	
	
	
}

/*Functions in Games ends
 * 
 * */



//Functions on votes begin

function check_vote($gameid, $voter_id, $votee_id, $type)
{
	if($type == 0)
	{
		$get_vote_query = "select * from votes where gameid = $gameid  and voter = $voter_id and votee = $votee_id and vote_type = 0";
	}
	else if ($type == 1)
	{
		$get_vote_query = "select * from votes where gameid = $gameid  and voter = $voter_id and votee = $votee_id and vote_type = 1";
	}

	
	$get_vote_result = pg_query($get_vote_query);
	
	if (pg_num_rows($get_vote_result) != 0)
	{
		return 1;
	}
	
	return 0;
	
}


function delete_vote($gameid, $voter_id, $votee_id)
{
	$delete_vote_query = "delete from votes where gameid = $gameid and voter =  $voter_id and votee = $votee_id";
	$delete_vote_result = pg_query($delete_vote_query);

	if($delete_vote_result)
	{
		//do nothing
	}
	else
	{
		echo "An error occurred, please go back to your previous page";
	}
	
	return true;
	
}


function update_vote($gameid, $voter_id, $votee_id, $vote_type_id)
{
	
	
	$vote_update_query = "update votes set vote_type = $vote_type_id where gameid = $gameid and voter =  $voter_id and votee = $votee_id";
	$vote_update_result = pg_query($vote_update_query);

	if($vote_update_result)
	{
		//do nothing
	}
	else
	{
		echo "An error occurred, please go back to your previous page";
	}
	
}


function add_vote($gameid, $voter_id, $votee_id, $vote_type)
{
	
	$exists = false;
	
	if($vote_type == 'like')
	{
		if(check_vote($gameid, $voter_id, $votee_id, 1))
		{
			
			decrement_like_dislike($votee_id, "dislike");
			
			update_vote($gameid, $voter_id, $votee_id, 0);
			$exists = true;
		}		
		increment_like_dislike($votee_id, "like");
		$vote_type_id = 0;
	}
	else if ($vote_type == 'dislike')
	{	
		
		if(check_vote($gameid, $voter_id, $votee_id, 0))
		{
			
			decrement_like_dislike($votee_id, "like");
			
			update_vote($gameid, $voter_id, $votee_id, 1);
			$exists = true;
		}
		increment_like_dislike($votee_id, "dislike");
		$vote_type_id = 1;
	}
	
	if(!$exists)
	{
	
		$vote_query = "insert into votes values ($gameid, $voter_id, $votee_id, $vote_type_id);";
		$vote_result = pg_query($vote_query);

		if($vote_result)
		{
			//do nothing
		}
		else
		{
			echo "An error occurred, please go back to your previous page";
		}
	}
	
}

function decrement_like_dislike($votee_id, $decrement_type)
{
	
	if($decrement_type == "like")
	{
		$dec_query = "update ratings set likes = likes -1 where userid =  $votee_id";
	}
	else if($decrement_type == "dislike")
	{
		$dec_query = "update ratings set dislikes = dislikes -1 where userid =  $votee_id";
	}
	
	
	$dec_result = pg_query($dec_query);

	if($dec_result)
	{
		//do nothing
	}
	else
	{
		echo "An error occurred, please go back to your previous page";
	}
	
	
}

function increment_like_dislike($votee_id, $increment_type)
{
	
	if($increment_type == "like")
	{
		$inc_query = "update ratings set likes = likes +1 where userid =  $votee_id";
	}
	else if($increment_type == "dislike")
	{
		$inc_query = "update ratings set dislikes = dislikes +1 where userid =  $votee_id";
	}
	
	
	$inc_result = pg_query($inc_query);

	if($inc_result)
	{
		//do nothing
	}
	else
	{
		echo "An error occurred, please go back to your previous page";
	}
	
	
}

//Functions on votes end

//Functions on register begin

function add_init_rating($userid)
{
	
	$add_init_rating_query = "insert into ratings values ($userid, 0, 0, 0);";
	$add_init_rating_result = pg_query($add_init_rating_query);

	if($add_init_rating_result)
	{
		//do nothing
	}
	else
	{
		echo "An error occurred, please go back to your previous page";
	}
	
}

function register ($name, $username, $password1, $password2, $email, $location_id, $skill, $sports) {

//		$location_Query="select location_name location from location where lid = ". $location_id;
//		$location_result = pg_query($location_Query);
		
		//To get a new ID number without conflicts
		$newID_Query="select max(userid)+1 newid from people";
		$newID_result = pg_query($newID_Query);

		$checkuser_Query="select count(*) num from people where username = '" .$username . "'";
		$checkuser_results = pg_query($checkuser_Query);
		$checkuser = pg_fetch_result($checkuser_results,0,0);
		
		//If username already taken
		if ($checkuser > 0){
			echo "<label>Username already taken, please try again</label>\n";
		//Check passwords match
		} elseif ($password1 != $password2) {
			echo "<label>Your passwords do not match, please try again</label>\n";
		} else {
			//Insert the form into DB
			while ($results = pg_fetch_assoc($newID_result)) 
			{
				$register_Query="insert into people values(".$results['newid']. ", '".$username . "', '".$password1."','".$name."','".$email."',".$location_id.",'" .$sports. "'," .$skill. ", 1)";
				$register_result = pg_query($register_Query);
				add_init_rating($results['newid']);
			}
			//Results of the insertion
			if($register_result)
			{
				echo "<label>Welcome ".$name. "! Your account was created successfully! Click on Login to go back</label>\n";
			}
			else
			{
				echo "<label>Account creation failed</label>\n";
			}
		}
}

//Functions on profile update info 

function update_info ($userid, $oldpass, $newpass1, $newpass2, $sports, $email) {
	
	$query = "SELECT count(*) num FROM people WHERE userid = ".$userid." AND password = '".$oldpass."' LIMIT 1";
	$result = pg_query($query);
	
	//If old password is wrong
	
	while ($rows = pg_fetch_assoc($result)) {
		if ($rows['num'] == 0) {
			echo "</br> <label>Wrong password, please try again</label>\n";
		//If new passwords don't match
		} elseif ($rows['num'] == 1 && ($newpass1 != $newpass2)) {
			echo "</br> <label>New passwords do not match, please try again</label>\n";	
		} else {
			$update_query = "UPDATE people SET password = '" .$newpass1. "', sport_interested = '" .$sports. "' , email = '" .$email. "' where userid = ".$userid;
			$update_result = pg_query($update_query);
			if ($update_result) {
				header("Location: Userprofile.php");
				echo "</br> <label>Information have succesfully updated</label>\n";
			}
		}
	}
}

//Function on admin update info

function update_info_admin ($userid, $oldpass, $newpass1, $newpass2, $email) {
	
	$query = "SELECT count(*) num FROM people WHERE userid = ".$userid." AND password = '".$oldpass."' LIMIT 1";
	$result = pg_query($query);
	
	//If old password is wrong
	while ($rows = pg_fetch_assoc($result)) {
		if ($rows['num'] == 0) {
			echo "</br> <label>Wrong password, please try again</label>\n";
		//If new passwords don't match
		} elseif ($rows['num'] == 1 && ($newpass1 != $newpass2)) {
			echo "</br> <label>New passwords do not match, please try again</label>\n";	
		} else {
			$update_query = "UPDATE people SET password = '" .$newpass1.  "' , email = '" .$email. "' where userid = ".$userid;
			$update_result = pg_query($update_query);
			if ($update_result) {
				echo "</br> <label>Information have succesfully updated</label>\n";
				header("Location: admin_profile.php");
			}
		}
	}
}


//Functions on login and authentication
function user_login ($username, $password) {

	// to prevent SQL injections
	$username = pg_escape_string($username);

	// See if the username/password combination exist in the table
	$query = "SELECT userid, admin_user FROM people WHERE username = '".$username."' AND password = '".$password."' LIMIT 1";
	$result = pg_query($query);

	// check to see if an entry was returned
	$rows = pg_num_rows($result);
	$data = pg_fetch_assoc($result);

	if ($rows<=0 ) {
		echo "Invalid username/password.  Please try again <br>";
		include("loginpage.php");
		exit();
	} else if ($rows=1){
		// they can login
		///echo "User type: ";
		$_SESSION['username'] = $username;
		$_SESSION['userid'] = $data['userid'];
		$_SESSION['type'] = $data['admin_user'];    //NEED WORK ON SETTING THE ADMIN USER TYPE
	} else {
		echo "ERROR";
		include("loginpage.php");
	}
}

function user_logout () {
	if(isset($_SESSION['userid'])) {
		unset($_SESSION['userid']);
	}
	if(isset($_SESSION['type'])) {
		unset($_SESSION['type']);
	}
	if(isset($_SESSION['time'])) {
		unset($_SESSION['time']);
	}
	//echo "You have logged out.";
	session_destroy();
}

function authenticate() {
    header('HTTP/1.0 401 Unauthorized');
    echo "You must log-in before accessing this resource\n";
    exit();
}

function authenticate_admin() {
	if(isset($_SESSION['type'])) {
		if ($_SESSION['type'] != 2) {
			header('HTTP/1.0 401 Unauthorized');
    			echo "You must be an administrator to access this resource.\n";
    			exit();			
		}
	} else {
		authenticate();
	}
}

function authenticate_player() {
	if(isset($_SESSION['type'])) {
		if ($_SESSION['type'] != 1) {
			header('HTTP/1.0 401 Unauthorized');
    			echo "You do not have permission to access this resource.\n";
    			exit();			
		}
	} else {
		authenticate();
	}
}

function check_inactive(){
	// set timeout period in seconds, 5 minute inactive limit
	//$inactive = 300;
	$inactive = 300;
	// check to see if $_SESSION['timeout'] is set
	if(isset($_SESSION['time']) ) {
		$session_life = time() - $_SESSION['time'];
		if($session_life > $inactive)
		{ 
			user_logout(); 
			echo "<script type='text/javascript'>
				alert('You have been inactive for over 10 minutes on this page, you will be log-out now.');
				window.parent.location='/svn/csc309/csc309/www/309/loginpage.php';
				</script>
				";		 
		}
	}
	$_SESSION['time'] = time();

}


?>
